var tablename = "course";
var app = this;
var $ = require("../../include/$");
module.exports = {
	get: function (req, res) {
		var data = req.query;
		var finner;
		if (data.coursetype == 1) {
			tablename = "coursecalendar";
			finner = req.models[tablename].find({ cid: data.cid });
		} else if (data.coursetype == 2) {
			tablename = "video";
			finner = req.models[tablename].find({ cid: data.cid });
		} else {
			tablename = "course";
			finner = req.models[tablename].find({}).limit(data.limit).offset(data.limit - 30);
		};
		console.log("查找:", tablename, "的数据");
		finner.run(function (err, result) {
			if (err) {
				res.send(500, err);
			} else if (!result.length) {
				res.send(404, "no found");
			} else {
				res.send(result);
			}
		});
	},
	post: function (req, res) {
		var data = req.body;
		req.models["studentcourse"].create($.extend({}, data.data), function (err, result) {
			if (err) {
				res.send(500, err);
			} else {
				console.log(result.ctype);
				if (result.ctype == 1) {
					console.log(data.course);
					// 学生添加日历课程
					req.models["calendar"].create(data.course, function (err, result) {
						if (err) {
							res.send(500, err);
						} else {
							res.send("ok");
							res.end();
						}
					});
				} else {
					//学生添加视频课程
					req.models["course"].get(result.cid, function (courseerr, course) {
						if (courseerr) {
							res.send(500, err);
						} else {
							var _arry = eval(course.sid);
							_arry.push(result.sid);
							course.sid = JSON.stringify(_arry);
							course.save(function (e) {
								if (e) { res.send(e); } else {
									res.send("ok"); res.end();
								}
							});
						}
					});
				}
			}
		});
	},
	delete: function (req, res) {
		var data = req.body;
		req.models["studentcourse"].find({ cid: data.cid }).remove(function (studentcourseerr) {
			if (studentcourseerr) {
				res.send(500, studentcourseerr);
			} else {
				if (data.coursetype == 1) {
					req.models["calendar"].find({ cid: data.cid, sid: data.sid }).remove(function (calendarerr) {
						if (calendarerr) {
							res.send(500, calendarerr);
							res.send("ok");
							res.end();
						}
					});
				} else {
					req.models["course"].get(data.cid, function (courseerr, course) {
						if (courseerr) {
							res.send(500, courseerr);
						} else {
							var _array = eval(course.sid);
							for (var i = 0; i < _array.length; i++) {
								if (_array[i] == data.sid) {
									_array.splice(i, 1);
								}
							}
							course.sid = JSON.stringify(_array);
							course.save(function (coursesveerr) {
								if (coursesveerr) {
									res.send(500, coursesveerr);
								} else {
									res.send("ok");
									res.end();
								}
							});
						}
					});
				}
			}
		});
	}
};